#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "libm_aux.h"

#define nrOpt 3

char *str_up(char *str)
{
  int i;

  for (i = 0; i < strlen(str); i++)
    {
      //If lowercase -> convert to uppercase, char by char.
      if (str[i] >= 'a' && str[i] <= 'z')
	str[i] = str[i] - 'a' + 'A';
    }

  return str;
}

int readLine(FILE *f, char *line, int len)
{
  char ch, *p_line = line;

  while ((ch = getc(f)) != '\n' && p_line - line < len)
    {
      //Skip carriage return '0x0D'.
      if (ch != '\r')
	*(p_line++) = ch;
    }

  *p_line = '\0';

  //Returns length of char-arr "line".
  return p_line - line;
}

int len_valid(int l_min, int l_max)
{
  if (l_min > l_max)
    return 0;

  if (l_min < lenMin || l_max > lenMax)
    return 0;

  return 1;
}

char *makeCharSet(char *opt, int *charSetLen)
{
  char *cSets[nrOpt] =
    {
      "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
      "0123456789",
      "~!?@#$%^&*"
    };

  int used[nrOpt];
  memset(used, 0, nrOpt * sizeof(int));

  int i, len = strlen(opt);
  if (len > nrOpt)
    return NULL;

  *charSetLen = 0;

  str_up(opt);
  for (i = 0; i < len; i++)
    {
      switch (opt[i])
	{
	case 'A': 
	  if (!used[0])
	    {
	      *charSetLen += strlen(cSets[0]);
	      used[0] = 1;
	    }
	  break;
	case 'N':
	  if (!used[1])
	    {
	      *charSetLen += strlen(cSets[1]);
	      used[1] = 1;
	    }
	  break;
	case 'S':
	  if (!used[2])
	    {
	      *charSetLen += strlen(cSets[2]);
	      used[2] = 1;
	    }
	  break;
	default:
	  return NULL;
	}
    }

  char *charSet = (char *) malloc(*charSetLen + 1);
  *charSet = '\0';

  for (i = 0; i < nrOpt; i++)
    {
      if (used[i])
	strcat(charSet, cSets[i]);
    }
  
  return charSet;
}
